﻿using Infrastructure;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.ServiceLocation;
using ViewsAndViewModels.Interfaces;
using ViewsAndViewModels.Views;

namespace ViewsAndViewModels.ViewModels
{
    public class MainMenuViewModel : ViewModelBase, IMainMenuViewModel
    {
        public DelegateCommand HelpAboutCommand { get; set; }
        public DelegateCommand HelpCommand { get; set; }
        public MainMenuViewModel(IMainMenuView view) :base(view)
        {
            HelpAboutCommand = new DelegateCommand(ExecuteHelpAboutCommand, CanExecuteHelpAboutCommand);
            HelpCommand = new DelegateCommand(ExecuteHelpCommand, CanExecuteHelpCommand);
            IEventAggregator ea = ServiceLocator.Current.GetInstance<IEventAggregator>();
            ea.GetEvent<ChangingMainContentView>().Subscribe(ChangingContentViewHandler);
        }
        private static void ExecuteHelpCommand(){}
        private static bool CanExecuteHelpCommand()
        {
            return CanExecuteHelpAboutCommand();
        }
        private void ChangingContentViewHandler(string obj)
        {
            HelpAboutCommand.RaiseCanExecuteChanged();
            HelpCommand.RaiseCanExecuteChanged();
        }
        private static void ExecuteHelpAboutCommand()
        {
            IRegionManager rm = ServiceLocator.Current.GetInstance<IRegionManager>();
            if (rm != null)
            {
                var aboutView = rm.Regions[RegionNames.ContentRegion].GetView(ViewNames.AboutViewName);
                rm.Regions[RegionNames.ContentRegion].Activate(aboutView);
                rm.Regions[RegionNames.ContentRegion].Context = ViewNames.AboutViewName;
                IEventAggregator ea = ServiceLocator.Current.GetInstance<IEventAggregator>();
                ea.GetEvent<ChangingMainContentView>().Publish(ViewNames.AboutViewName);
            }
        }
        private static bool CanExecuteHelpAboutCommand()
        {
            IRegionManager rm = ServiceLocator.Current.GetInstance<IRegionManager>();
            if (rm != null)
            {
                if (string.CompareOrdinal(ViewNames.AboutViewName, rm.Regions[RegionNames.ContentRegion].Context.ToString()) == 0)
                {
                    return false;
                }
                return true;
            }
            return true;
        }
    }
}
